import { readOnly, parsePath } from './utils';
/**
 * 暴露history对象
 */
let listeners: any[] = [];

let location = {};
const getLocation = () => {
  const { pathname, search, hash } = window.location;
  return readOnly({
    pathname,
    search,
    hash,
    state: null,
  });
};

function getNextLocation(to: string, state = null) {
  return readOnly({
    ...parsePath(to),
    state,
  });
};

const push = (to: string, state: any) => {
  location = getNextLocation(to, state);
  window.history.pushState(state, '', to);
  listeners.forEach((listener: any) => listener(location));
};

const listen = (fn: any) => {
  listeners.push(fn);
  return () => {
    listeners = listeners.filter((listener) => listener !== fn);
  };
};

window.addEventListener('popstate', () => {
  location = getLocation();
  listeners.forEach((listener: any) => listener(location));
})

export const history: any = {
  get location() {
    return location;
  },
  push,
  listen,
};
